package com.gdk.ksoft.assembly.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.assembly.receiver.UploadNotifyReciever;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.lidroid.xutils.DbUtils;

/**
 * Created by Mrper on 2014/11/22.
 * 后台进程任务前台服务
 */
public class ForegroundService extends Service {

    private Thread uploadThread = null;//更新数据的线程
    /**
     * 通知后台开启检测、现数据上传的通知
     */
    private UploadNotifyReciever uploadNotifyReciever;

    /**
     * 后台是否允许线程运行的标志
     */
    private boolean flag = false;

    /**
     * 数据库操作对象
     */
    private DbUtils dbUtils = null;

    /**
     * 上下文对象
     */
    public Context context = null;

    /**
     * 注册通知开始上传后台数据通知
     */
    public void registeReceiver(){
        uploadNotifyReciever = new UploadNotifyReciever(new UploadNotifyReciever.OnUploadStateChangedListener() {
            @Override
            public void onUploadStateChanged(boolean isOpenUpload) {
//                openOrStopUpload(isOpenUpload);//开启或者停止数据上传
            }
        });
        IntentFilter filter = new IntentFilter(UploadNotifyReciever.ACTION);
        this.registerReceiver(uploadNotifyReciever,filter);
    }

    /**
     * 开启或者停止数据上传
     * @param isOpenUpload
     */
    public void openOrStopUpload(boolean isOpenUpload){
        if(isOpenUpload) {
            try {
                if (flag) return;//当前任务已经在运行了，不需要再运行
                flag = true;
                startUpload();//开始上传后台记录
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                if(!flag) return;//当前任务已经停止，不需要再执行停止
                flag = false;
                if(uploadThread!=null){//终止线程的运行
                    uploadThread.interrupt();
                    uploadThread = null;//上传线程置为空
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public ForegroundService() {
        super();
    }

    /**
     * 创建后台进程
     */
    public void createBackgroundProcess() {
        Notification notification = new Notification();
        notification.defaults = Notification.DEFAULT_LIGHTS;
        notification.icon = R.drawable.ic_launcher;
        notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
        PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        notification.setLatestEventInfo(this, "管得宽-业务管理软件", "正在后台运行", intent);
        startForeground(1, notification);//设置为前台通知
    }

    /**
     * 上传后台数据
     */
    public void startUpload() {
        uploadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(flag){
                    try{
                        Thread.sleep(ConstantData.UPLOAD_DATA_TIMER*60*1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        TaskUtils.requestOrderNo(context,dbUtils, true);//请求销售单单据号
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        TaskUtils.requestOrderNo(context,dbUtils, false);//请求退货单单据号
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        TaskUtils.uploadDeliverGoodsAddress(context,dbUtils);//上传送货地址经纬度地址到服务器
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        TaskUtils.uploadSaleOrders(context,dbUtils);//上传销售单及其商品信息
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try{
                        TaskUtils.uploadDeliverAddress(context,dbUtils);//上传客户收货地址
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try{
                        TaskUtils.uploadCustomerInformation(context,dbUtils);//上传修改过的客户信息
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
        uploadThread.start();//开始执行数据上传
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = ForegroundService.this;//获取上下文对象
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();//数据库操作对象
        createBackgroundProcess();//创建后台进程
        registeReceiver();//上传数据操作
        return Service.START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        flag = false;//停止线程运行的标志
        if(uploadNotifyReciever!=null)
            this.unregisterReceiver(uploadNotifyReciever);
        stopForeground(true);
        stopSelf();
        super.onDestroy();
    }
}
